import { Component, OnInit } from '@angular/core';
import { NavController, AlertController } from '@ionic/angular';
import { HttpService } from 'src/app/service/http.service';
import { PopwinService } from 'src/app/service/popwin.service';
import { UrlService } from 'src/app/service/url.service';
import { ConfigService } from 'src/app/service/config.service';
import { ToolService } from 'src/app/service/tool.service';
import { Storage } from '@ionic/storage';
import * as $ from 'jquery';

// import * as AlloyCrop from "alloycrop";


@Component({
  selector: 'app-personalcenter',
  templateUrl: './personalcenter.page.html',
  styleUrls: ['./personalcenter.page.scss'],
})
export class PersonalcenterPage implements OnInit {
  public uinfoData = { "showname": "","images":"", "phone": "", "realname": "", "email": "", "sex": '', "birthday2": '0000-00-00', "password": "", "password2": "","qq":"","wechatid":"" };
  public selectData: any;
  private username = "";
  constructor(private navCtrl: NavController, private http: HttpService, private popWin: PopwinService, private alertCtrl: AlertController, private store: Storage) { }

  ngOnInit() {
    let that = this;
    this.store.get(ConfigService.ROLE_KEY).then((data) => {
      if (data == '2') {
        that.popWin.toast("试玩账号不能进入");
        that.backClick();
        return;
      }
      that.personalData();
    });
    this.uploadAvatar();

  }
  /**
   * 上传用户的头像
   */
  uploadAvatar() {
    let that=this;
    let input = document.querySelector('input[type=file]');
    input.addEventListener('change', function (e) {
      let file = this.files[0];
      let reader = new FileReader();
      reader.onload = function () {
        let url = reader.result;
        //对图片进行裁剪
        new AlloyCrop({
          image_src: url,
          className:"alloy-crop-box",
          width: 200,
          height: 200,
          output: 1,
          circle: false,
          ok_text: "上传",
          cancel_text: "取消",
          ok: function (base64, canvas) {
            $("input[type=file]").val("");
             that.uploadAvatarData(base64);
             e.stopPropagation();
          },
          cancel: function () {
            console.log('取消剪裁')
            e.stopPropagation();
          }
        });
      };
      reader.readAsDataURL(file);
    })
  }


  uploadAvatarData(data){
    let that = this;
    let obj = "{\"file\":\"" + data + "\"}";
    let token = $("app-root").attr("token");
    let sessid = $("app-root").attr("sessid");
    let uid = $("app-root").attr("uid");
    let encrypt = (!ToolService.isEmpty($("app-root").attr("encrypt")) && $("app-root").attr("encrypt") == '1') ? 1 : 0;
    let baseParam;
    if (ToolService.isEmpty(sessid)) {
      baseParam = { "token": ToolService.isEmpty(token) ? "" : token, "data": ToolService.aesEncode(obj), "tross": "createorder", "encrypt": encrypt,"uid": uid,"v":ConfigService.APP_VERSION };   
    } else {
      baseParam = { "token": ToolService.isEmpty(token) ? "" : token, "sessid": sessid, "data": ToolService.aesEncode(obj), "tross": "createorder", "encrypt": encrypt,"uid": uid,"v":ConfigService.APP_VERSION };
    }
    var api = ConfigService.SERVER_PATH + UrlService.OTHER_UPLOAD;
    $.ajax({
      url: api, data: baseParam, dataType: 'json', success: function (res) {
        let data = res
        if (data.code == ConfigService.SUCCESS_CODE) {
          //成功的逻辑
          let tempData = ToolService.aesDecodeToJson(data.data);
          console.log("成功后的输出结果:", tempData);
          that.store.set(ConfigService.USERINFO_KEY,tempData);
          that.userInfo();
        } else if (data.code == ConfigService.FAIL_CODE) {
          that.popWin.toast(data.message);
        } else if (data.code == ConfigService.LOGIN_CODE) {
          that.navCtrl.navigateForward("/login");
        } else if (data.code == ConfigService.BET_CHANGE_RATE) {
          that.popWin.toast(data.message);
        } else {
          that.popWin.toast(data.message);
        }
      }, complete: function () {

      }, type: 'POST'
    });

  }


  userInfo() {
    let that=this;
    this.store.get(ConfigService.USERINFO_KEY).then((data) => {
      let tempUserInfo = data;
      if (!ToolService.isEmpty(tempUserInfo)) {
        that.uinfoData=tempUserInfo.uinfo;
      }
    });

  }

  backClick() {
    this.navCtrl.navigateBack("tabs/my");
  }

  personalData() {
    let that = this;
    this.http.get(UrlService.USER_SHOWUSERINFO, { "callback": "JSONP_CALLBACK" }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let temp = data.data;
        let res = ToolService.aesDecodeToJson(temp);
        console.log(res);
        if (!ToolService.isEmpty(res.uinfo)) {
          that.uinfoData = res.uinfo;
          that.selectData = that.uinfoData.birthday2;
        }
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }
  /**
   * 修改用户的信息
   * @param type input表单的类型
   * @param value 新输入的表单值
   */
  rechangeInfo(type, value) {
    let that = this;
    let obj = {};
    if (type == 'email') {
      if (!ToolService.isEmail(value)) {
        this.popWin.toast("邮箱格式不正确");
        return;
      }
      obj = "{\"email\":\"" + value + "\"}";
    } else if (type == 'showname') {
      if (ToolService.isEmpty(value)) {
        this.popWin.toast("昵称不能为空");
        return;
      }
      obj = "{\"showname\":\"" + value + "\"}";
    } else if (type == 'sex') {
      obj = "{\"uval\":\{\"sex\":\"" + value + "\"}\}";
    } else if (type == 'realname') {
      if (ToolService.isEmpty(value)) {
        this.popWin.toast("真是姓名不为空");
        return;
      }
      obj = "{\"uval\":\{\"realname\":\"" + value + "\"}\}";
    } else if (type == 'birthday') {
      obj = "{\"uval\":\{\"birthday\":\"" + that.selectData.substr(0, 10) + "\"}\}";
    } else if (type == 'password2') {
      obj = "{\"password2\":\"" + value + "\"}";
    } else if (type == 'phone') {
      // obj = "{\"uval\":\{\"phone\":\"" + value + "\"}\}";
      obj = "{\"phone\":\"" + value + "\"}";
    }else if(type == 'qq'){
      if (ToolService.isEmpty(value)) {
        this.popWin.toast("qq号不能为空");
        return;
      }
      obj = "{\"qq\":\"" + value + "\"}";
    }else if(type == 'wechatid'){
      if (ToolService.isEmpty(value)) {
        this.popWin.toast("微信号不能为空");
        return;
      }
      obj = "{\"wechatid\":\"" + value + "\"}";
    }
    this.alertCtrl.dismiss();
    this.http.get(UrlService.USER_EDITUSERINFO, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let temp = data.data;
        let res = ToolService.aesDecodeToJson(temp);
        if (!ToolService.isEmpty(res)) {
          that.uinfoData = res;
        }
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  showBankList() {
    this.navCtrl.navigateForward("/banklist");
  }


  async baseAlert(header: string, value: string, type: string, inputType?: "number" | "date" | "email" | "password" | "search" | "tel" | "text" | "url" | "time" | "checkbox" | "radio") {
    let that = this;
    const alert = await this.alertCtrl.create({
      header: header,
      inputs: [
        {
          name: 'base',
          type: inputType ? inputType : 'text',
          value: value
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => { }
        }, {
          text: '确认',
          handler: (data) => {
            that.rechangeInfo(type, data.base);
            return false;
          }
        }
      ]
    });
    await alert.present();
  }

  modifyPsw(type, psw1, psw2) {
    let that = this;
    let obj = {};
    if (type == 'tpassword') {//修改登录密码
      obj = "{\"oldpassword\":\"" + psw1 + "\",\"password\":\"" + psw2 + "\"}";
    } else if (type == 'tpassword2') {//修改支付密码
      obj = "{\"oldpassword2\":\"" + psw1 + "\",\"password2\":\"" + psw2 + "\"}";
    }
    this.http.get(UrlService.USER_EDITUSERINFO, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        that.popWin.toast(data.message);
        if (type == 'tpassword') {
          that.store.clear();
          that.store.remove("token");
          $("app-root").removeAttr("token");
          $("app-root").removeAttr("sessid");
          $("app-root").removeAttr("uid");
          that.navCtrl.navigateRoot("/");
        }
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }
  async baseTwoAlert(header: string, placeholderStr: string, type: string) {
    let that = this;
    const alert = await this.alertCtrl.create({
      header: header,
      inputs: [
        {
          name: 'psw1',
          type: 'password',
          placeholder: "原来" + placeholderStr + "密码"
        },
        {
          name: 'psw2',
          type: 'password',
          placeholder: "新" + placeholderStr + "密码"
        }, {
          name: 'psw3',
          type: 'password',
          placeholder: "重复新" + placeholderStr + "密码"
        }
      ],
      buttons: type == 'tpassword' ? [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: () => { }
      }, {
        text: '确认',
        handler: (data) => {
          that.baseTwoAlertData(type, data.psw1, data.psw2, data.psw3);
          return false;
        }
      }] : [
          {
            text: '取消',
            role: 'cancel',
            handler: () => { }
          }, {
            text: '找回密码',
            handler: () => {
              that.findPaypswAlert();
            }
          }, {
            text: '确认',
            handler: (data) => {
              that.baseTwoAlertData(type, data.psw1, data.psw2, data.psw3);
              return false;
            }
          }
        ]
    });
    await alert.present();
  }
  baseTwoAlertData(type, psw1, psw2, psw3) {
    let that = this;
    if (ToolService.isEmpty(psw1) || ToolService.isEmpty(psw2) || ToolService.isEmpty(psw3)) {
      that.popWin.toast("密码必须输入");
      return;
    }
    if (!ToolService.isEmpty(psw2) && !ToolService.isEmpty(psw3) && psw2 != psw3) {
      that.popWin.toast("两次输入的新密码不一致");
      return;
    }
    if (!ToolService.isEmpty(psw2) && !ToolService.isEmpty(psw3) && psw2 == psw3 && !ToolService.isEmpty(psw1)) {
      //可以处理
      this.alertCtrl.dismiss();
      that.modifyPsw(type, psw1, psw2);
    }
  }
  async sexAlertRadio(val) {
    let that = this;
    const alert = await this.alertCtrl.create({
      header: '修改性别',
      inputs: [
        {
          name: 'sex2',
          type: 'radio',
          label: '男',
          value: '2',
          checked: val != '1' ? true : false
        },
        {
          name: 'sex1',
          type: 'radio',
          label: '女',
          value: '1',
          checked: val == '1' ? true : false
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => { }
        }, {
          text: '确定',
          handler: (data) => {
            that.rechangeInfo('sex', data);
          }
        }
      ]
    });
    await alert.present();
  }

  async findPaypswAlert() {
    let that = this;
    const alert = await this.alertCtrl.create({
      header: "找回支付密码",
      backdropDismiss: false,
      inputs: [
        {
          name: 'username',
          type: 'text',
          placeholder: "输入用户名",
          value: that.username
        },
        {
          name: 'code',
          type: 'text',
          placeholder: "输入邮箱验证码"
        }, {
          name: 'psw',
          type: 'password',
          placeholder: "输入新支付密码"
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
            that.username = "";
          }
        }, {
          text: '获取邮箱验证码',
          handler: (data) => {
            that.username = data.username;
            that.getCode(data.username);
            return false;
          }
        }, {
          text: '确认',
          handler: (data) => {
            that.username = "";
            that.submitFindPSw(data.username, data.code, data.psw);
            return false;
          }
        }
      ]
    });
    await alert.present();
  }

  submitFindPSw(username, code, password) {
    if (ToolService.isEmpty(username)) {
      this.popWin.toast("用户名必须输入");
      return;
    }
    if (ToolService.isEmpty(code)) {
      this.popWin.toast("邮箱验证码须输入");
      return;
    }
    if (ToolService.isEmpty(password)) {
      this.popWin.toast("新支付必须输入");
      return;
    }
    let that = this;
    let obj = "{\"username\":\"" + username + "\",\"type\":\"charge\",\"code\":\"" + code + "\",\"password\":\"" + password + "\"}";
    this.http.get(UrlService.LOGIN_MODIFYPWD, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        that.popWin.toast(data.message);
        that.alertCtrl.dismiss();
      } else {
        that.popWin.toast(data.message);
      }
    }, error => {
      that.popWin.toast(ToolService.newError(error));
    });
  }
  /**
   * 获取邮箱验证码
   */
  getCode(username) {
    let that = this;
    if (ToolService.isEmpty(username)) {
      that.popWin.toast("用户名必须输入");
      return;
    }
    let obj = "{\"username\":\"" + username + "\",\"type\":\"charge\"}";
    this.http.get(UrlService.LOGIN_FINDPWD, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        that.popWin.toast(data.message);
        let tempRes = ToolService.aesDecodeToJson(data.data);
        // that.gap = tempRes.gap;
        // clearInterval(this.timer01);
        // that.count(that.gap);
      } else {
        that.popWin.toast(data.message);
      }
    }, error => {
      that.popWin.toast(ToolService.newError(error));
    });
  }

}
